<template>
    <div>
        <div class="rule-head">

        </div>
        <div class="rule-main">
            <div class="rule-left">
                <el-card class="operate-container" shadow="never">
                    <span class="btn-list">文档名称</span>
                    <div>
                        <el-button v-if="!isTwoS" size="mini" class="btn-add" @click="handleSortTwo()" >排序</el-button>
                        <el-button v-if="isTwoS" size="mini" class="btn-add" @click="handleSortTwoC()" >取消</el-button>
                        <el-button style="background-color: #4099ef;color: #fff;" v-if="isTwoS" size="mini" class="btn-add" @click="handleSortTwoS()" >提交</el-button>
                        <el-button size="mini" class="btn-add" @click="handleAddTwo()" >添加文档</el-button>
                    </div>
                </el-card>
                <div class="table-container">
                    <el-table ref="firstTable"
                                :data="listQ"
                                row-key="id"
                                @row-click="handleRowClick"
                                :row-class-name="tableRowClassName"
                                v-loading="listLoading" border>
                        <el-table-column label="拖拽排序" align="center">
                            <template slot-scope="scope">
                                <i class="el-icon-s-operation"></i>
                            </template>
                        </el-table-column>
                        <el-table-column label="文档名称（繁体中文）" align="center">
                            <template slot-scope="scope">{{scope.row.titleZhHk}}</template>
                        </el-table-column>
                        <el-table-column label="现行版本" align="center">
                            <template slot-scope="scope">{{scope.row.version}}</template>
                        </el-table-column>
                        <el-table-column label="复制链接" align="center">
                            <template slot-scope="scope">
                                <i class="el-icon-paperclip" style="color: #409EFF;cursor: pointer;" @click="handleApk(scope.$index, scope.row)"></i>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="180" align="center">
                            <template slot-scope="scope">
                                <el-button size="mini"
                                        type="text"
                                        @click="handleEditeP(scope.$index, scope.row)">发布
                                </el-button>
                                <el-button size="mini"
                                        type="text"
                                        @click="handleEditeQ(scope.$index, scope.row)">编辑
                                </el-button>
                                <el-button size="mini"
                                        type="text"
                                        @click="handleDelete(scope.$index, scope.row, 2)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <div class="rule-right">
                <el-card class="operate-container" shadow="never">
                    <span class="btn-list">版本号</span>
                    <div>
                        <el-button size="mini" class="btn-add" @click="handleAdd()" >添加版本</el-button>
                    </div>
                </el-card>
                <div class="table-container">
                    <el-table ref="firstTable"
                                :data="listLei"
                                style="width: 100%;"
                                v-loading="listLoading" border>
                        <el-table-column label="版本号" align="center">
                            <template slot-scope="scope">
                                {{ scope.row.version }}
                                <span v-if="scope.row.active" style="color: green;">(现行版本)</span>
                            </template>
                        </el-table-column>
                        <el-table-column align="center">
                            <template slot="header">
                                协议强提醒
                                <el-tooltip class="item" effect="dark" content="出弹窗再次获取同意，每次打开APP均弹出，同意则继续使用APP，不同意则退出APP" placement="top">
                                    <i class="el-icon-question"></i>
                                </el-tooltip>
                            </template>
                            <template slot-scope="scope">{{scope.row.forceUpgrade ? '是': '否'}}</template>
                        </el-table-column>
                        <el-table-column label="最近修改时间/创建时间" align="center">
                            <template slot-scope="scope">{{scope.row.updateTime | formatDateTime}}</template>
                        </el-table-column>
                        <el-table-column label="操作" width="180" align="center">
                            <template slot-scope="scope">
                                <el-button v-if="!scope.row.active" size="mini"
                                        type="text"
                                        @click="handleEdite(scope.$index, scope.row)">编辑
                                </el-button>
                                <el-button v-if="!scope.row.active" size="mini"
                                        type="text"
                                        @click="handleDelete(scope.$index, scope.row, 3)">删除
                                </el-button>
                                <span v-if="scope.row.active">编辑</span>
                                <span v-if="scope.row.active">删除</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>

        <el-dialog
            title="添加/编辑文档"
            :visible.sync="cagVisible"
            width="40%">
            <el-form :model="addCag"
                    :rules="rules"
                    ref="cagForm"
                    label-width="180px" size="small"  class="demo-ruleForm">
                <el-form-item label="文档名称（繁体中文）：" prop="titleZhHk">
                    <el-input v-model="addCag.titleZhHk" style="width: 250px"></el-input>
                </el-form-item>
                <el-form-item label="文档名称（简体中文）：" prop="titleZhCn">
                    <el-input v-model="addCag.titleZhCn" style="width: 250px"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cagVisible = false" size="small">取 消</el-button>
                <el-button type="primary" @click="handlePublishDocConfirm('cagForm')" size="small">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog
            title="发布现行版本"
            :visible.sync="publishVisible"
            width="40%">
            <el-form :model="publishList"
                    ref="publishForm"
                    label-width="180px" size="small">
                <el-form-item label="文档名称：">
                    <span>{{ publishList.titleZhHk }}</span>
                </el-form-item>
                <el-form-item label="选择版本：">
                    <el-select v-model="publishId" placeholder="请选择版本号">
                        <el-option
                            v-for="item in listLei"
                            :key="item.id"
                            :label="item.version"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="生效时间：">
                    <span>立即生效</span>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="publishVisible = false" size="small">取 消</el-button>
                <el-button type="primary" @click="handlePublishConfirm('publishForm')" size="small">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog
            title="添加/编辑文档版本"
            :visible.sync="docVisible"
            width="75%">
            <el-form :model="publishDocList"
                    ref="publishForm"
                    :rules="ruleDoc"
                    label-width="200px" size="small">
                <el-form-item label="选择所属文档：">
                    <el-select v-model="publishDocList.docId" placeholder="请选择所属文档">
                        <el-option
                            v-for="item in listQ"
                            :key="item.id"
                            :label="item.titleZhHk"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="版本号：" prop="version">
                    <el-input v-model="publishDocList.version" style="width: 250px"></el-input>
                </el-form-item>
                <el-form-item label="弹窗介绍内容（繁体中文）: " prop="contentZhHk" label-width="105px">
                    <EditorHK :height="300" v-model="publishDocList.contentZhHk"></EditorHK>
                </el-form-item>
                <el-form-item label="弹窗介绍内容（简体中文）: " prop="contentZhCn" label-width="105px">
                    <Editor :height="300" v-model="publishDocList.contentZhCn"></Editor>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer" style="display: flex;justify-content: end;align-items: center;padding-right: 50px;">
                <div class="is-force">
                    <el-checkbox v-model="publishDocList.forceUpgrade" @change="changeBox"></el-checkbox>
                    <span>发布时是否强提示</span>
                    <i class="el-icon-question"></i>
                </div>
                <el-button @click="docVisible = false" size="small">取 消</el-button>
                <el-button type="primary" @click="handlePublishDoc('publishForm')" size="small">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import { ruleDocList, ruleVerList, ruleDocAdd, ruleDocDelete, ruleDocUpdate, ruleContentAdd, ruleContentUpdate, rulePublish, ruleSort, fetchAllResourceList } from '@/api/app';
import {formatDate} from '@/utils/date';
import Editor from '@/components/Editor';
import EditorHK from '@/components/EditorHK';
import Sortable from 'sortablejs';
export default {
    name: 'rule',
    components: {
        Editor,
        EditorHK,
    },
    data() {
        return {
            listLoading: false,
            listQ: [],
            listLei: [],
            verQuery: {
                pageNum: 1,
                pageSize: -1,
                docId: null
            },
            isAdd: true,
            cagVisible: false,
            addCag: {
                titleZhHk: null,
                titleZhCn: null
            },
            rules: {
                titleZhHk: [
                    { required: true, message: '请填写文档名称（繁体中文）' }
                ],
                titleZhCn: [
                    { required: true, message: '请填写文档名称（简体中文）' }
                ],
            },
            ruleDoc: {
                docId: [
                    { required: true, message: '请选择文档' }
                ],
                version: [
                    { required: true, message: '请填写版本号' }
                ],
                contentZhHk: [
                    { required: true, message: '请填写文档名称（繁体中文）' }
                ],
                contentZhCn: [
                    { required: true, message: '请填写文档名称（简体中文）' }
                ],
            },
            publishVisible: false,
            publishList: {
                titleZhHk: null
            },
            publishId: null,
            docVisible: false,
            publishDocList: {
                docId: null,
                contentZhHk: null,
                contentZhCn: null,
                version: null,
                forceUpgrade: true,
            },
            isTwoS: false,
            currentRow: {id: null},
            sortShow: null,
            btnMenu: {
                edit: true,
                delete: true,
            },
        }
    },
    created() {
        const menu = JSON.parse(localStorage.getItem('listMenu'));
        const item = menu.filter(item => item.title === '规则与条款')[0];
        fetchAllResourceList({menuId: item.id }).then(res => {
            res.data.forEach(dom => {
            if (dom.component === '' && dom.name === '后台角色管理') {
                this.btnMenu.edit = false;
            }
            if (dom.component === '' && dom.name === '后台角色删除') {
                this.btnMenu.delete = false;
            }
            });
        });
        this.docInfo();
    },
    mounted() {
        // this.$nextTick(() => {
        //     const el = this.$el.querySelector('.el-table__body-wrapper tbody');
        //     Sortable.create(el, {
        //         onEnd: (event) => {
        //             const { oldIndex, newIndex } = event;
        //             this.rowDrop(oldIndex, newIndex);
        //         }
        //     })
        // });
    },
    filters: {
        formatDateTime(time) {
          if (time == null || time === '') {
            return '-';
          }
          let date = new Date(time);
          return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
        }
    },
    methods: {
        handleRowClick(row, column, event) {
            this.verQuery.docId = row['id'];
            this.verInfo();
            this.currentRow = row;
        },
        tableRowClassName({row, rowIndex}) {
            if (row.id === this.currentRow['id']) {
                return 'current-row';
            }
            return '';
        },
        changeBox(e) {
            if (!e) {
                this.$confirm('你确定要取消强提示吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                }, () => {
                    this.addList.forceUpgrade = true;
                });
            }
        },
        rowDrop(oldIndex, newIndex) {
            this.isTwoS = true;
            const movedItem = this.listQ.splice(oldIndex, 1)[0];
            this.listQ.splice(newIndex, 0, movedItem);
            // console.log(this.listQ);
        },
        handlePublishConfirm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    rulePublish({id: this.publishId}).then(res => {
                        this.publishVisible = false;
                        this.docInfo();
                    })
                } else {
                    return false;
                }
            });
        },
        handlePublishDoc(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.isAdd) {
                        ruleContentAdd(this.publishDocList).then(res => {
                            this.docVisible = false;
                            this.docInfo();
                        })
                    } else {
                        ruleContentUpdate(this.publishDocList).then(res => {
                            this.docVisible = false;
                            this.docInfo();
                        })
                    }
                } else {
                    return false;
                }
            });
        },
        handlePublishDocConfirm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.isAdd) {
                        ruleDocAdd(this.addCag).then(res => {
                            this.cagVisible = false;
                            this.docInfo();
                        })
                    } else {
                        ruleDocUpdate(this.addCag).then(res => {
                            this.cagVisible = false;
                            this.docInfo();
                        })
                    }
                } else {
                    return false;
                }
            });
        },
        docInfo() {
            ruleDocList({ pageNum: 1, pageSize: -1 }).then(res => {
                this.listQ = res.data.records;
                if (this.listQ.length > 0) {
                    this.verQuery.docId = this.listQ[0]['id'];
                    this.currentRow.id = this.listQ[0]['id'];
                    this.verInfo();
                }
            });
        },
        verInfo() {
            ruleVerList(this.verQuery).then(res => {
                this.listLei = res.data.records;
            });
        },
        handleSortTwo() {
            const el = this.$el.querySelector('.el-table__body-wrapper tbody');
            this.sortShow = Sortable.create(el, {
                onEnd: (event) => {
                    const { oldIndex, newIndex } = event;
                    this.rowDrop(oldIndex, newIndex);
                }
            })
            this.isTwoS = true;
        },
        handleSortTwoC() {
            this.isTwoS = false;
            this.sortShow.destroy();
            this.docInfo();
        },
        handleSortTwoS() {
            ruleSort(this.listQ).then(res => {
                this.isTwoS = false;
                this.sortShow.destroy()
                this.docInfo();
                this.$message({
                    type: 'success',
                    message: '排序成功!'
                });
            });
        },
        handleAddTwo() {
            this.addCag = {
                titleZhHk: null,
                titleZhCn: null
            };
            this.cagVisible = true;
            this.isAdd = true;
        },
        handleAdd() {
            this.publishDocList = {
                docId: null,
                contentZhHk: null,
                contentZhCn: null,
                version: null,
                forceUpgrade: true,
            };
            this.docVisible = true;
            this.isAdd = true;
        },
        async handleApk(index, row) {
            try {
                await navigator.clipboard.writeText(row.urlZhHk);
                this.$message({
                    type: 'success',
                    message: '链接已复制！'
                });
            } catch (error) {
                // console.log('复制失败');
            }
        },
        handleEditeP(index, row) {
            if (this.listLei.length > 0) {
                this.publishList = row;
                this.publishVisible = true;
            } else {
                this.$message({
                    type: 'error',
                    message: '当前文档暂无版本号，请先添加版本号!'
                });
            }
        },
        handleEditeQ(index, row) {
            this.cagVisible = true;
            this.addCag = JSON.parse(JSON.stringify(row));
            this.isAdd = false;
        },
        handleEdite(index, row) {
            this.docVisible = true;
            this.publishDocList = JSON.parse(JSON.stringify(row));
            this.isAdd = false;
        },
        handleDelete(index, row, type) {
            this.$confirm('是否要删除该数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                ruleDocDelete({id: row.id, type: type}).then(response => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.docInfo();
                });
            });
        },
    }
}
</script>

<style lang="scss" scoped>
.current-row {
  background-color: #f0f9eb;
}
.rule-head {
    // padding: 40px;
    display: flex;
    justify-content: space-between;
}
.rule-main {
    display: flex;
    padding: 0 20px;
    .rule-left {
        flex: 1;
        margin-right: 20px;
    }
    .rule-right {
        width: 550px;
    }
}
.is-force {
    margin-right: 10px;
    color: #3e3e3e;
    font-size: 14px;
}
</style>
